<style lang="scss">
.z-search-table-con.is-not-load {
  overflow: hidden;
}
.z-search-table__form {
  //margin-bottom: 10px;
  .el-form-item {
    margin-bottom: 0;
  }
  .dym-form .el-form-item__label {
    width: auto !important;
    padding-left: 10px;
  }
}
.z-table__search-actions {
  padding-top: 0;
}
.z-search-table-con {
  height: var(--z-search-table-con-h);
}
.z-search-table-inner {
  height: var(--z-search-table-inner-h);
}
.z-search-table-no {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

<template>
  <div class="z-search-table-con"
  :class="{'is-not-load': !state.showTable}"
  >
<!--    {{dataTable.state.columns}}-->
    <div
        class="z-search-table"
        :id="tool.id"
        v-batch-select="{ selector: tool.selector,

        getScrollY: tool.getScrollY,
        selectIdxs: tool.state.selectIdxs }"
    >
      <slot name="table__inner__beforebegin"></slot>
      <slot name="table__content_beforeform"></slot>
      <div class="z-search-table__form-con" :hidden="hiddenForm">
<!--        {{dataTable.search.slots}}-->
        <z-form-template
            v-if="state.inited"
            :inline="true"
            :label-inline="true"
            :slots="dataTable.search.slots"
            :def="dataTable.search.def"
            class="z-search-table__form"
            :ref="getRef"
            @fire="dataTable.onFire">
        </z-form-template>
      </div>
      <slot name="table__form__afterend"   v-if="state.inited"></slot>
      <div class="z-search-table-inner"
          v-show="state.showTable && dataTable.state && dataTable.state.columns && dataTable.state.columns.length > 0">
        <slot name="table__content_beforebegin"></slot>
        <div class="z-search-table__content">
          <slot name="table__content_afterbegin"></slot>
          <slot name="table__table_beforebegin"></slot>
          <z-table
              ref="zTable"
              :table-attrs="{stripe: true, ...tableAttrs}"
              v-loading="dataTable.state.loading"
              :columns="dataTable.state.columns"
              :data="dataTable.state.result.records"
              :current-page.sync="dataTable.state.result.current"
              :page-size.sync="dataTable.state.result.size"
              :total="dataTable.state.result.total"
              :selectable="selectable"
              :radioable="radioable"
              :sequence="sequence"
              :height="heightMode"
              :selectableWidth="selectableWidth"
              :sequenceWidth="sequenceWidth"
              :row-class-name="tableRowClassName"
              @row-click="handleRowClick"
              :render-content="renderContent"
              @page-change="handlePageChange"
              @cur-radio-change="fireChange('cur-radio-change', $event)"
              @selection-change="fireChange('selection-change', $event)"
              @scroll-to-bottom="fireChange('scroll-to-bottom', $event)"
          >
            <template v-slot:action="scope"><slot name="table__action" v-bind="scope"></slot></template>
            <template v-slot:page_before="scope"><slot name="table__page_before"></slot></template>
            <template v-slot:column="scope">
              <slot name="table__column" v-bind="scope"></slot>
              <template v-if="scope.prop === 'TABLE_ROW_CHECK'">
              <textarea class="el-table__row-check"
                        style="height: 0; padding: 0; width: 0; border: none"
                        :data-uuid="scope.row.id"
                        batch-select-dataset>{{scope.row}}</textarea>
              </template>
            </template>
          </z-table>
          <slot name="table__table_afterend"></slot>
          <slot name="table__content_beforeend"></slot>
        </div>
        <slot name="table__content_afterend"></slot>
      </div>
      <div class="z-search-table-no-data"
           v-if="!state.showTable"
      >
        <div class="z-search-table-no-data__inner">
          <div class="z-search-table-no" v-show="state.inited">
            <slot name="table__no__data" v-bind="exportScope">暂无数据</slot>
          </div>
          <div class="z-search-table-err" v-if="state.curErr">{{state.curErr}}</div>
        </div>
      </div>
      <slot name="table__inner__afterend"></slot>
    </div>

  </div>
</template>

<script>

import {useGridBatchSelect} from "../../../../babel-static/hooks";

export default {
  name: 'ZSearchTable',
  components: {},
  props: {
    def: null,
    tableAttrs: {
      type: Object,
      default() {
        return {}
      }
    },
    submitEventName: {
      type: String,
      default: 'form-submit'
    },
    resetEventName: {
      type: String,
      default: 'form-reset'
    },
    rowClassName: Function,
    autoInit: {
      type: Boolean,
      default: true
    },
    selectable:{
      type: Boolean,
      default: false
    },
    selectableWidth: null,
    sequenceWidth: null,
    sequence: {
      type: Boolean,
      default: true
    },
    radioable: {
      type: Boolean,
      default: false
    },
    hiddenForm: {
      type: Boolean,
      default: false
    },
    heightMode: {
      type: String,
      default: 'auto'
    },
    renderContent: null,
    onInit: null
  },
  methods: {
    getElTable() {
      return this.$refs.zTable.$_getTable()
    },
    handleRowClick(...args) {
      this.tool.tableRowClick(...args);
      // console.log('handleRowClick',args)
      this.$emit('single-row-click', args)
    },
  },
  data() {
    return {
      initSearch: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.initSearch = true
      }, 300)
    })
  },
  setup(props, ctx) {
    const { onMounted, reactive } = globalThis.vueCompositionAPI

    let curForm = null;
    let dataTable = props.def;

    let state = reactive({
      inited: false,
      showTable: false,
      curErr: ''
    })

    function getDef() {
      return dataTable
    }


    function getSearchData() {
      let data = {}
      if (curForm && curForm.getCurForm) {
        let form = curForm.getCurForm();
        // console.log('search',curForm, form)
        if (form) {
          data = form.getDataSyncV2();
        }
      }
      return data
    }

    async function search(reqOptions = {}) {
      let {params, ...rest} = reqOptions
      let data = {}
      if (curForm && curForm.getCurForm) {
        let form = curForm.getCurForm();
        // console.log('search',curForm, form)
        if (form) {
          // let [isValid, errors] = await form.submit();
          // // console.log(isValid, errors)
          // if (isValid) {
          //   data = await form.getDataSyncV2();
          //   // console.log(data)
          //   // console.log('search', data)
          // }

          data = await form.getDataSyncV2();
        }
      }
      dataTable.req({
        params: {
          ...data,
          ...params
        },
        ...rest
      }).then(() => {
        setTimeout(() => {
          state.showTable = true;
        }, 100)
        state.inited = true;
      }).catch((e) => {
        if (dataTable.onReqErr) {
          dataTable.onReqErr(e)
        }
        state.curErr = e;
        state.inited = true;
        console.log('err', e)
      })
      return 1;
    }

    // form的事件处理
    dataTable.onFire = function ([type, args] = []) {
      if (type === props.submitEventName) {
        // console.log('submitEventName', args)
        search()
      }
      if (type === props.resetEventName) {
        // console.log('reset')
        ctx.emit('search-form-reset')
      }
    }

    async function load(res) {
      await dataTable.load(res);
      await ZY.sleep(100);
      state.showTable = true
    }

    function fireChange(name, e) {
      ctx.emit(name, e)
    }


    let tool = useGridBatchSelect(props, ctx, {
      getAppScrollY: window.getZAppScrollY
    })


    function tableRowClassName(...args) {
      let ret = tool.tableRowClassName(...args)
      if (props.rowClassName) {
        ret = ret + props.rowClassName(...args)
      }
      return ret
    }

    function getTool() {
      return tool
    }

    function cancelSelect() {
      tool.cancelSelect()
      console.log('cancelSelect')
    }

    let exportScope = {
      state,
      getSearchData
    }

    function getRef(el) {
      // console.log('getRef', el)
      curForm = el
    }

    function handlePageChange(e) {
      dataTable.handlePageChange(e, {
        params: exportScope.getSearchData()
      })
    }

    let ret = {
      state,
      getRef,
      load,
      getTool,
      handlePageChange,
      exportScope,
      cancelSelect,
      tableRowClassName,
      dataTable,
      tool,
      getDef,
      fireChange,
      search,
    }

    onMounted(async () => {

      // console.log(props.autoInit)
      if (props.autoInit) {
        if (dataTable.canRequest()) {
          search()
        }
      }
      if (props.onInit) {
        props.onInit(ret)
      }
    })



    return ret
  }
}
</script>
